package com.zzh.custom;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;


import com.zzh.tools.listener.ToolOnClickListener;
import com.zzh.tools.system.ToolScreen;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author zhangzhihao
 * @email zhangzhihao@gongjiangren.net
 * @date 2020-08-04
 * @desc 图片放大view
 */
public class PictureBrowseView extends FrameLayout {

    // 下部变动标识的模式
    private int pointModel;
    // 关闭按钮图片
    private int closeImageId;

    // 配置参数使用
    private Config mConfig;
    // 依赖其他方使用
    private Rely mRely;
    // 添加自定义指示
    private InstructionsPoint mInstructionsPoint;
    // 自定义指示器父布局
    private ViewGroup mInstructionsPointViewGroup;
    // 第一次显示的索引
    private int mPosition = 0;

    public interface Rely {
        void load(ImageView imageView, String path, String smallPath);

        void load(ImageView imageView, int drawId);
    }

    public interface Config {
        Fragment newFragment();

        List<Map<String, String>> getList();

        int getShowPosition();

    }

    public interface InstructionsPoint {
        ViewGroup getView(Context context);

        void slidView(ViewGroup viewGroup, int position);
    }

    public PictureBrowseView setConfig(Config config) {
        this.mConfig = config;
        return this;
    }

    public PictureBrowseView setRely(Rely rely) {
        this.mRely = rely;
        return this;
    }

    public PictureBrowseView setPosition(int position) {
        this.mPosition = position;
        return this;
    }

    public PictureBrowseView(@NonNull Context context) {
        this(context, null);
    }

    public PictureBrowseView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PictureBrowseView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    /**
     * 初始化参数
     *
     * @param context
     * @param attrs
     */
    private void init(Context context, @Nullable AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typeArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PictureBrowseView, 0, 0);
            pointModel = typeArray.getInt(R.styleable.PictureBrowseView_pageTagModel, 0);
            closeImageId = typeArray.getResourceId(R.styleable.PictureBrowseView_closeIcon, -1);
            typeArray.recycle();
        }

    }

    public void show() {
        addView(createRootView((FragmentActivity) getContext()));
    }

    private View createRootView(FragmentActivity context) {
        View rootView = LayoutInflater.from(context).inflate(R.layout.layout_picture_browse, null);
        ViewPager viewPager = rootView.findViewById(R.id.picture_browse);
        LinearLayout tagView = rootView.findViewById(R.id.picture_browse_tag);
        ImageView closeImage = rootView.findViewById(R.id.picture_browse_close);
        if (closeImageId > 0) {
            closeImage.setOnClickListener(new ToolOnClickListener() {
                @Override
                public void onClick(View v) {
                    super.onClick(v);
                    if (id == -1) {
                        return;
                    }
                    context.finish();
                }
            });
            closeImage.setImageResource(closeImageId);
        }
        PagerAdapter pagerAdapter = createAdapter(context);
        if (pointModel == 1) {
            tagView.addView(createCountView(context, pagerAdapter.getCount()));
        } else if (pointModel == 2) {
            tagView.addView(createPointView(context, pagerAdapter.getCount()));
        } else {
            if (mInstructionsPoint != null) {
                mInstructionsPointViewGroup = mInstructionsPoint.getView(context);
                if (mInstructionsPointViewGroup != null) {
                    tagView.addView(mInstructionsPointViewGroup);
                } else {
                    tagView.setVisibility(View.GONE);
                }
            } else {
                tagView.setVisibility(View.GONE);
            }
        }
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (pointModel == 1) {
                    mTvCount.setText(String.valueOf(position + 1));
                } else if (pointModel == 2) {
                    for (int i = 0; i < mVgPointView.getChildCount(); i++) {
                        mVgPointView.getChildAt(i).setBackgroundResource(i == position ? R.drawable.tool_corners_ffffff_solid15 : R.drawable.tool_corners_666666_solid15);
                    }
                } else {
                    if (mInstructionsPoint != null) {
                        mInstructionsPoint.slidView(mInstructionsPointViewGroup, position);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        if (mConfig != null) {
            viewPager.setCurrentItem(mConfig.getShowPosition());
        }
        return rootView;
    }


    private TextView mTvCount;

    private View createCountView(Context context, int allCount) {
        View countView = LayoutInflater.from(context).inflate(R.layout.pb_count_tag, null);
        mTvCount = countView.findViewById(R.id.count);
        ((TextView) countView.findViewById(R.id.allCount)).setText(String.format("/%d", allCount));
        return countView;
    }

    private ViewGroup mVgPointView;

    private View createPointView(Context context, int allCount) {
        mVgPointView = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.pb_point_tag, null);
        int pointSize = ToolScreen.dip2px(context, 10);
        int pointInterval = ToolScreen.dip2px(context, 5);
        for (int i = 0; i < allCount; i++) {
            View point = new View(context);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(pointSize, pointSize);
            layoutParams.setMargins(pointInterval, 0, 0, 0);
            point.setLayoutParams(layoutParams);
            point.setBackgroundResource(i == 0 ? R.drawable.tool_corners_ffffff_solid15 : R.drawable.tool_corners_666666_solid15);
            mVgPointView.addView(point);
        }
        return mVgPointView;
    }

    private PagerAdapter createAdapter(FragmentActivity context) {
        PagerAdapter pagerAdapter = new MyPageAdapter(context.getSupportFragmentManager(), mConfig == null ? null : mConfig.getList());
        return pagerAdapter;
    }

    class MyPageAdapter extends FragmentPagerAdapter {
        private List<Map<String, String>> mList;
        private Map<Integer, Fragment> fragmentMap;

        @SuppressLint("WrongConstant")
        public MyPageAdapter(@NonNull FragmentManager fm, List<Map<String, String>> list) {
            super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
            this.mList = list;
            fragmentMap = new HashMap<>(mList.size() * 2);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            if (!fragmentMap.containsKey(position)) {
                Fragment fragment = mConfig == null ? new DefaultFragment() : mConfig.newFragment();
                if (fragment == null) {
                    fragment = new DefaultFragment();
                }
                if (fragment instanceof DefaultFragment) {
                    ((DefaultFragment) fragment).setRely(mRely);
                }
                Map<String, String> map = mList.get(position);
                Bundle bundle = new Bundle();
                for (Map.Entry<String, String> stringEntry : map.entrySet()) {
                    bundle.putString(stringEntry.getKey(), stringEntry.getValue());
                }
                bundle.putInt("position", position);
                fragment.setArguments(bundle);
                fragmentMap.put(position, fragment);
            }
            return fragmentMap == null ? null : fragmentMap.get(position);
        }

        @Override
        public int getCount() {
            return mList == null ? 0 : mList.size();
        }
    }


    public static class DefaultFragment extends Fragment {

        private Rely mRely;

        private int position;
        private String url;
        private String smallUrl;
        private int drawId;

        private View mRootView;

        public void setRely(Rely rely) {
            this.mRely = rely;
        }

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            argments();
            if (mRootView == null) {
                mRootView = LayoutInflater.from(container.getContext()).inflate(R.layout.pb_default_fragment, null);
                setClick(mRootView.findViewById(R.id.showImage));
            }
            if (mRely != null) {
                if (!TextUtils.isEmpty(url)) {
                    mRely.load(mRootView.findViewById(R.id.showImage), url, smallUrl);
                } else if (drawId > 0) {
                    mRely.load(mRootView.findViewById(R.id.showImage), drawId);
                } else {
                    //不做处理
                }
            }
            return mRootView;
        }

        private void setClick(View view) {
            view.setOnClickListener(new ToolOnClickListener() {
                @Override
                public void onClick(View v) {
                    super.onClick(v);
                    if (id == -1) {
                        return;
                    }
                    Context context = getContext();
                    if (context instanceof Activity) {
                        ((Activity) context).finish();
                    }
                }
            });
        }


        private void argments() {
            Bundle bundle = getArguments();
            position = bundle.getInt("position");
            url = bundle.getString("url");
            smallUrl = bundle.getString("smallUrl");
            String drawStr = bundle.getString("drawId");
            if (!TextUtils.isEmpty(drawStr)) {
                drawId = Integer.valueOf(drawStr);
            }
        }
    }

}
